//
// Created by jinbang.li on 2023/7/1.
//
extern "C"
{
#include <libswresample/swresample.h>
#include <libavcodec/avcodec.h>
}
#include "OpFFResample.h"
#include "../Log/OpLog.h"

bool OpFFResample::Open(OpParameter in,OpParameter out ){
    actx = swr_alloc();
    //in.parameters->sample_rat 22050  44100 重采样变小音会改变
    actx = swr_alloc_set_opts(actx, av_get_default_channel_layout(2),
                              AV_SAMPLE_FMT_S16,
                              out.sample_rate,
                              av_get_default_channel_layout(in.parameters->channels),
                              (AVSampleFormat)in.parameters->format,
                              in.parameters->sample_rate,0,0);
    int re = swr_init(actx);
    if (re != 0){
        OPLOGE("swr_init failed");
        return false;
    }
    outChannels = in.parameters->channels;
    outFormat = AV_SAMPLE_FMT_S16;
    return true;
}
OpData  OpFFResample::Resample(OpData indata){
    if (indata.size <= 0 || !indata.data) return OpData();
    if (!actx){
        return OpData();
    }

    //输出空间的分配
    AVFrame *frame = (AVFrame *)indata.data;

    OpData out;
    int outSize = outChannels * frame->nb_samples * av_get_bytes_per_sample((AVSampleFormat)outFormat);
    if (outSize <= 0) return OpData();
    out.alloc(outSize);
    uint8_t *outArr[2] ={0};
    outArr[0] = out.data;
    int len = swr_convert(actx,outArr,frame->nb_samples,(const uint8_t **)frame->data,frame->nb_samples);
    if (len <= 0){
        OPLOGE("swr_convert failed");
        out.dropData();
        return OpData();
    }

    return out;
}